package com.jiangchao.mimidao.framework.factory;

import com.jiangchao.mimidao.framework.aop.MimiDaoHandler;
import java.lang.annotation.Annotation;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.beans.factory.support.GenericBeanDefinition;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

public class MimiDaoScannerConfiguretion implements BeanDefinitionRegistryPostProcessor {

  private String basePackages;

  /**
   * 默认使用@Repository注解作为识别入口，且不允许自定义其他入口
   */
  private Class<? extends Annotation> annotation = Repository.class;
  /**
   * 是否格式化sql
   */
  private boolean formatSql = false;
  /**
   * 是否输出sql
   */
  private boolean showSql = false;

  public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry beanDefinitionRegistry)
      throws BeansException {
    registerRequestProxyHandler(beanDefinitionRegistry);
    MimiDaoScanner scanner = new MimiDaoScanner(beanDefinitionRegistry, Repository.class);
    scanner.scan(StringUtils.tokenizeToStringArray(basePackages,
        ConfigurableApplicationContext.CONFIG_LOCATION_DELIMITERS));
  }

  public void postProcessBeanFactory(
      ConfigurableListableBeanFactory configurableListableBeanFactory) throws BeansException {

  }

  private void registerRequestProxyHandler(BeanDefinitionRegistry registry) {
    GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition();
    genericBeanDefinition.setBeanClass(MimiDaoHandler.class);
    genericBeanDefinition.getPropertyValues().add("formatSql",formatSql);
    genericBeanDefinition.getPropertyValues().add("showSql",showSql);
    registry.registerBeanDefinition("mimiDaoHandler", genericBeanDefinition);
  }

  public String getBasePackages() {
    return basePackages;
  }

  public void setBasePackages(String basePackages) {
    this.basePackages = basePackages;
  }

  public Class<? extends Annotation> getAnnotation() {
    return annotation;
  }

  public void setAnnotation(Class<? extends Annotation> annotation) {
    this.annotation = annotation;
  }

  public boolean isFormatSql() {
    return formatSql;
  }

  public void setFormatSql(boolean formatSql) {
    this.formatSql = formatSql;
  }

  public boolean isShowSql() {
    return showSql;
  }

  public void setShowSql(boolean showSql) {
    this.showSql = showSql;
  }
}
